package com.fhz.day018.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

import com.fhz.day018.Song;
import com.fhz.day018.utils.SongDataUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MusicService extends Service {
    private MediaPlayer mediaPlayer;
    private List<Song> songList;
    private int index =0;
    public MusicService() {
    }

    public class MyBinder extends Binder{
        public void callPlay(int i){
            play(i);
        }

        public MusicService getService(){
            return MusicService.this;
        }

    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //只执行一次. 适合初始化资源
        mediaPlayer = new MediaPlayer();
        songList =  SongDataUtil.getSongDataUtil().getDataList(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return super.onStartCommand(intent, flags, startId);
    }

    public void play(int i){
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(songList.get(i).getData());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void next(){
        //
    }

    public void pre(){

    }

    public int getCurrentPostion(){
        return mediaPlayer.getCurrentPosition();
    }

    public int getMax(){
        return Integer.parseInt(songList.get(index).getDuration());
    }


}